﻿using System;
using GalaSoft.MvvmLight;
using Drafter.Model;
using System.Collections.Generic;
using System.Windows.Documents;
using System.Text;
using System.Windows;
using System.IO;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;

namespace Drafter.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class DraftViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the DraftViewModel class.
        /// </summary>
        public DraftViewModel()
        {
            //if (IsInDesignMode)
            //{
                CreateDummyData();
            // }
            //else
            //{
            //    // Code runs "for real": Connect to service, etc...
            //}
                InitializeCommands();
        }

        private void CreateDummyData()
        {
            _draft = new Draft()
            {
                Title = "Draft de Prueba",
                RootChapters = new List<Chapter>(){
                        new Chapter(){
                            Title="Capitulo1",
                            Text="Texto del Capitulo 1",
                            Notes="Notas del Capitulo 1",
                             ChildChapters = new ObservableCollection<Chapter>(){
                                        new Chapter(){
                                            Title="Capitulo1.1",
                                            Text="Texto del Capitulo 1.1",
                                            Notes="Notas del Capitulo 1.1"
                                            
                                        },
                                        new Chapter(){
                                            Title="Capitulo1.2",
                                            Text="Texto del Capitulo 1.2",
                                            Notes="Notas del Capitulo 1.2"
                                            
                                        },
                             }
                        },
                        new Chapter(){
                            Title="Capitulo2",
                            Text="Texto del Capitulo 2",
                            Notes="Notas del Capitulo 2"
                        }

                    }
            };
            LoadRootChapters();
        }

        ////public override void Cleanup()
        ////{
        ////    // Clean own resources if needed

        ////    base.Cleanup();
        ////}

        //TODO developers please add your constructors in the below constructor region.
        //     be sure to include an overloaded constructor that takes a model type.

        #region Commands
        public RelayCommand<object> CreateRootChapterCommand
        {
            get;
            private set;
        }

        private void InitializeCommands()
        {
            CreateRootChapterCommand = new RelayCommand<object>((item) =>
            {
                ChapterViewModel selectedChapter = (ChapterViewModel)item;
                ChapterViewModel selectedRootChapter = getRootChapter(selectedChapter);


                int position = 0;
                if (selectedChapter != null)
                {
                    position = this.RootChapters.IndexOf(selectedRootChapter)+1;
                }

                Chapter c = new Chapter() { Title = "New" };
                _draft.RootChapters.Insert(position,c);

                ChapterViewModel cvm = new ChapterViewModel(c, null);

                this.RootChapters.Insert(position,cvm);
               
            });
        }

        private ChapterViewModel getRootChapter(ChapterViewModel selectedChapter)
        {
            if (selectedChapter.Parent == null)
            {
                return selectedChapter;
            }
            else
            {
                return getRootChapter(selectedChapter.Parent as ChapterViewModel);
            }
        }
        #endregion

        #region Declarations

        private Draft _draft;

        #endregion //Declarations

        #region Properties

        public ObservableCollection<ChapterViewModel> RootChapters { get; set; }

        public String Title
        {
            get { return _draft.Title; }
            set
            {
                _draft.Title = value;
                RaisePropertyChanged("Title");
            }
        }

        public void Save(string filename)
        {
            Draft.WriteToFile(filename, this._draft);
        }

        public void Load(string filename)
        {
            this._draft=Draft.ReadFromFile(filename);
            LoadRootChapters();
            RaisePropertyChanged("Title");
            RaisePropertyChanged("RootChapters");
        }

        private void LoadRootChapters()
        {
            this.RootChapters = new ObservableCollection<ChapterViewModel>();
            foreach (Chapter chapter in _draft.RootChapters)
            {
                ChapterViewModel cvm= new ChapterViewModel(chapter, null);
                this.RootChapters.Add(cvm);
            }
        }
        #endregion //Properties


        public DocumentPaginator GetPaginator()
        {
            string allChapters = getAllChaptersText();

            FlowDocument flowDocument = new FlowDocument();
            foreach (string line in allChapters.Split('\n'))
            {
                Paragraph myParagraph = new Paragraph();
                myParagraph.Margin = new Thickness(0);
                myParagraph.Inlines.Add(new Run(line));
                flowDocument.Blocks.Add(myParagraph);
            }
            DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
            return paginator;
        }

        private string getAllChaptersText()
        {
            StringBuilder sb = new StringBuilder();
            foreach (Chapter chapter in _draft.RootChapters)
            {
                chapter.AppendChapterTreeText(sb);
            }
            return sb.ToString();
        }


        internal void Export(string filename)
        {
            string allChapters = getAllChaptersText();

            TextWriter tw = null;
            try
            {
                tw = new StreamWriter(filename);
                tw.Write(allChapters);
            }
            finally
            {
                tw.Close();
            }

   
        }
    }
}